/**
  ******************************************************************************
  * File Name          : terminal.c
  * Description        : Code for terminal applications
  ******************************************************************************
  * @attention
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "tskcfg.h"
#include "bsp.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TTY_RXBUF_MAXLEN           40
#define TTYRECV_QUE_LENGTH         3
#define TTYRECV_QUE_ITEMSIZE       (sizeof(uint8_t) * TTY_RXBUF_MAXLEN)

typedef enum
{
	TTY_HEADER1  = 0u,
	TTY_HEADER2,
	TTY_PAYLOAD,
	TTY_0A,
}tty_recvstattype;

QueueHandle_t        TTYRecv_qhd;
static StaticQueue_t ttyrecv_stru;
static uint8_t       ttyrecv_area[ TTYRECV_QUE_LENGTH * TTYRECV_QUE_ITEMSIZE ];

TaskHandle_t xTerminal_Thd = NULL;
StaticTask_t xTerminal_Tcb;
StackType_t  xTerminal_Stk[ TTY_STACK_SIZE ];

static volatile	tty_recvstattype tty_recv_stat;
static char tty_isrbuf[TTY_RXBUF_MAXLEN];
static char tty_rcvbuf[TTY_RXBUF_MAXLEN];


void vTerminal_Task( void * pvParameters )
{
	const char *p;
	TTYRecv_qhd = xQueueCreateStatic(TTYRECV_QUE_LENGTH,
	                                 TTYRECV_QUE_ITEMSIZE,
	                                 ttyrecv_area,
	                                 &ttyrecv_stru);
	while(1)
	{
		if(xQueueReceive(TTYRecv_qhd, &tty_rcvbuf, portMAX_DELAY) == pdTRUE)
		{
			p = strstr( tty_rcvbuf, "TIME");
			if( p != NULL)
			{
				_printf("%04d-%02d-%02d %02d:%02d:%02d\r\n", Sys_Runtime.year+2000, Sys_Runtime.month,\
																										 Sys_Runtime.day, Sys_Runtime.hour,\
																										 Sys_Runtime.minute, Sys_Runtime.second);
			}
		}
	}
}

void Terminal_RecvIsr(uint8_t dat)
{
	static uint32_t count;
	
	switch(tty_recv_stat)
	{
		case TTY_HEADER1:
			if(dat == ';')
			{
				tty_recv_stat = TTY_HEADER2;
			}
			break;
		
		case TTY_HEADER2:
			if(dat == ';')
			{
				tty_recv_stat = TTY_PAYLOAD;
				count = 0;
			}
			else
			{
				tty_recv_stat = TTY_HEADER1;
			}
			break;
		
		case TTY_PAYLOAD:
			if(dat == 0x0du)
			{
				tty_recv_stat = TTY_0A;
			}
			else
			{
				tty_isrbuf[count++] = dat;
				if(count > (TTY_RXBUF_MAXLEN-4))
				{
					tty_recv_stat = TTY_HEADER1;
				}
			}
			break;
		
		case TTY_0A:
			if(dat == 0x0au)
			{
				tty_isrbuf[count] = 0;
				if(TTYRecv_qhd != NULL)
				{
					xQueueSendFromISR(TTYRecv_qhd, &tty_isrbuf, NULL);
				}
			}
			tty_recv_stat = TTY_HEADER1;
			break;
		
		default:
			tty_recv_stat = TTY_HEADER1;
			break;
	}
}

void Terminal_BreakIsr(void)
{
	tty_recv_stat = TTY_HEADER1;
}
